package net.risesoft.risebi.collection.web.admin;

import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.risesoft.risebi.collection.commons.constants.SystemConstants;
import net.risesoft.risebi.commons.util.sqlfilter.JsonFilterResolver;
import net.risesoft.risebi.collection.commons.hibernate.HibernateLoader;
import net.risesoft.risebi.collection.event.eventobj.EventObject;
import net.risesoft.risebi.collection.event.eventobj.SystemLogEventObj;
import net.risesoft.risebi.collection.model.Catalog;
import net.risesoft.risebi.collection.model.DbColumn;
import net.risesoft.risebi.collection.model.Service;
import net.risesoft.risebi.collection.model.SystemLog;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.CatalogManager;
import net.risesoft.risebi.collection.service.DbMetaDataManager;
import net.risesoft.risebi.collection.service.DynaBeanManager;
import net.risesoft.risebi.collection.service.ReportInstanceManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.hibernateextension.HibernateUtil;
import net.risesoft.risebi.commons.util.ContextUtil;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

/**
*
* @author <a href="mailto: dingzhaojun2046@hotmail.com">丁兆俊</a>
* @version $Revision$
* 
*/
@Namespace("/admin/CatalogCrudAction")
public class CatalogCrudAction extends BaseAction {
	private static final long serialVersionUID = 4601872459020725857L;
	
	private CatalogManager catalogManager;
	private DbMetaDataManager dbMetaDataManager;
	private DynaBeanManager dynaBeanManager;
	private HibernateLoader hibernateLoader;	
	private ReportInstanceManager reportInstanceManager;
	
	private Catalog catalog;	
	private HashMap<String,Object> dynaBean;	
	
	private String field; //Ext.ux.plugins.RemoteValidator
	private String value; //Ext.ux.plugins.RemoteValidator
	private String crud;
	private String catalogCode;
	
	private String item_guid;
	private String item_parentguid;
	private String filter;
	
	@Action(value="remove")
	public String remove() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		LazyDynaBean ldb = new  LazyDynaBean();
		
		try{
			Integer count = reportInstanceManager.getCount("select count(*) from ReportInstance r "
					+ "where r.soInstanceGuid='" + this.item_guid + "' and r.status>0");
			if (count > 0) {				
				ldb.set("success", false);
				ldb.set("reason", "该填报用户已经有了填报数据，不允许删除，请在报表查询中先删除该报表的填报数据后再删除该用户。");
			}else{
				User user = this.getSessionUser();
				Object item = dynaBeanManager.getObject(tableName, this.item_guid);				
				dynaBeanManager.removeObject(tableName, this.item_guid);				
				
	//    		记录日志
	    		SystemLog systemLog = new SystemLog();
	    		systemLog.setOpterateType(SystemLog.OPTERATETYPE_REMOVE);
	    		systemLog.setUser(user);
	    		
	    		Service service = this.getDefaultService();
	    		systemLog.setServiceGuid(service.getGuid());
	    		
	    		EventObject systemLogEventObject = new SystemLogEventObj(this);
	    		Map systemLogMap = new HashMap();
	    		systemLogMap.put("systemLog", systemLog);
	    		systemLogMap.put("keyName", "catalogitemremove");
	    		systemLogMap.put("catalog", catalog);
	    		systemLogMap.put("obj", item);
	    		
	    		systemLogEventObject.setDataMap(systemLogMap);
	    		ContextUtil.getAc().publishEvent(systemLogEventObject);
				
				ldb.set("success", true);
				ldb.set("reason", "删除成功!");
			}
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		return AJAX;
	}

	@Action(value="createDictType")
	public String createDictType() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		String item_type = this.source.trim();
		LazyDynaBean ldb = new  LazyDynaBean();
		
		try{
			dynaBean = new HashMap<String,Object>();
			String guid = new GUID().toString();
			dynaBean.put("item_guid", guid);
			dynaBean.put("item_code", "new code");
			dynaBean.put("item_name", "new name");
			dynaBean.put("item_type", item_type);
			dynaBean.put("tabindex", new Double(1));
			dynaBeanManager.saveObject(tableName, dynaBean);
			
			User user = this.getSessionUser();
			
//    		记录日志
    		SystemLog systemLog = new SystemLog();
    		systemLog.setOpterateType(SystemLog.OPTERATETYPE_ADD);
    		systemLog.setUser(user);
    		
    		Service service = this.getDefaultService();
    		systemLog.setServiceGuid(service.getGuid());
    		
    		EventObject systemLogEventObject = new SystemLogEventObj(this);
    		Map systemLogMap = new HashMap();
    		systemLogMap.put("systemLog", systemLog);
    		systemLogMap.put("keyName", "dicttypeadd");
    		systemLogMap.put("catalog", catalog);
    		systemLogMap.put("item_type", item_type);
    		
    		systemLogEventObject.setDataMap(systemLogMap);
    		ContextUtil.getAc().publishEvent(systemLogEventObject);
			
			ldb.set("success", true);
			ldb.set("reason", "增加字典类别成功!");
			ldb.set("guid", item_type);
			ldb.set("item_type", item_type);
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		
		return AJAX;
	}

	@Action(value="saveDictItems")
	public String saveDictItems() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
			String tableName = catalog.getTableName().trim().toLowerCase();
			
			HashMap<String,Object>[] maps = (HashMap<String,Object>[])JSONUtil.stringToArray(json, HashMap.class);
			String names = "";
			for (HashMap<String,Object> map : maps){
				String item_guid = (String)map.get("item_guid");
				boolean newed = false;
				if(item_guid==null || item_guid.trim().length()==0 || item_guid.startsWith("NEW")){
					map.put("item_guid",new GUID().toString());
					newed = true;
				}
				//dynaBeanManager.saveObject(tableName,map);
				dynaBeanManager.saveObject(tableName,HibernateUtil.convertType(tableName, map,SystemConstants.REPORT_DYNAMODEL));
				
				User user = this.getSessionUser();
				
//        		记录日志
				SystemLog systemLog = new SystemLog();
        		if(newed)
        			systemLog.setOpterateType(SystemLog.OPTERATETYPE_ADD);
        		else
        			systemLog.setOpterateType(SystemLog.OPTERATETYPE_EDIT);
        		systemLog.setUser(user);
        		
        		Service service = this.getDefaultService();
        		systemLog.setServiceGuid(service.getGuid());
        		
        		EventObject systemLogEventObject = new SystemLogEventObj(this);
        		Map systemLogMap = new HashMap();
        		systemLogMap.put("systemLog", systemLog);
        		if(newed)
        			systemLogMap.put("keyName", "dictitemadd");
        		else
        			systemLogMap.put("keyName", "dictitemedit");
        		systemLogMap.put("catalog", catalog);
        		systemLogMap.put("obj", map);
        		
        		systemLogEventObject.setDataMap(systemLogMap);
        		ContextUtil.getAc().publishEvent(systemLogEventObject);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存字典条目成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="saveSoItem")
	public String saveSoItem() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		LazyDynaBean ldb = new  LazyDynaBean();
		
		try{
			Object tabindex = dynaBean.get("tabindex");
			if(tabindex!=null){
				try{
					dynaBean.put("tabindex",Double.parseDouble(tabindex.toString()));
				}catch(Exception e){
					dynaBean.put("tabindex",1d);
				}
			}
			
			User user = this.getSessionUser();
			
			if("c".equals(this.crud)){				
				dynaBeanManager.saveObject(tableName, HibernateUtil.convertType(tableName, dynaBean,SystemConstants.REPORT_DYNAMODEL));	
				ldb.set("item_guid", dynaBean.get("item_guid"));
				ldb.set("item_parentguid", dynaBean.get("item_parentguid"));
				ldb.set("item_code", dynaBean.get("item_code"));
				ldb.set("item_name", dynaBean.get("item_name"));
				ldb.set("tabindex", dynaBean.get("tabindex"));
				
//        		记录日志
				SystemLog systemLog = new SystemLog();
        		systemLog.setOpterateType(SystemLog.OPTERATETYPE_ADD);
        		systemLog.setUser(user);
        		
        		Service service = this.getDefaultService();
        		systemLog.setServiceGuid(service.getGuid());
        		
        		EventObject systemLogEventObject = new SystemLogEventObj(this);
        		Map systemLogMap = new HashMap();
        		systemLogMap.put("systemLog", systemLog);
        		systemLogMap.put("keyName", "soitemadd");
        		systemLogMap.put("catalog", catalog);
        		systemLogMap.put("obj", dynaBean);
        		
        		systemLogEventObject.setDataMap(systemLogMap);
        		ContextUtil.getAc().publishEvent(systemLogEventObject);
			}else{
				HashMap<String,Object> dynaBeanOld = (HashMap<String,Object>)dynaBeanManager.getObject(tableName, (String)dynaBean.get("item_guid"));
				dynaBean = (HashMap<String,Object>)HibernateUtil.convertType(tableName, dynaBean,SystemConstants.REPORT_DYNAMODEL);
				for(String key : dynaBeanOld.keySet()){
					if(dynaBean.containsKey(key) && dynaBean.get(key)!=null){
						dynaBeanOld.put(key, dynaBean.get(key));
					}
				}
				dynaBeanManager.saveObject(tableName, dynaBeanOld);	
				ldb.set("item_guid", dynaBean.get("item_guid"));
				ldb.set("item_parentguid", dynaBean.get("item_parentguid"));
				ldb.set("item_code", dynaBeanOld.get("item_code"));
				ldb.set("item_name", dynaBeanOld.get("item_name"));
				ldb.set("tabindex", dynaBeanOld.get("tabindex"));
				
//        		记录日志
				SystemLog systemLog = new SystemLog();
        		systemLog.setOpterateType(SystemLog.OPTERATETYPE_EDIT);
        		systemLog.setUser(user);
        		
        		Service service = this.getDefaultService();
        		systemLog.setServiceGuid(service.getGuid());
        		
        		EventObject systemLogEventObject = new SystemLogEventObj(this);
        		Map systemLogMap = new HashMap();
        		systemLogMap.put("systemLog", systemLog);
        		systemLogMap.put("keyName", "soitemedit");
        		systemLogMap.put("catalog", catalog);
        		systemLogMap.put("obj", dynaBeanOld);
        		
        		systemLogEventObject.setDataMap(systemLogMap);
        		ContextUtil.getAc().publishEvent(systemLogEventObject);
			}
				
			ldb.set("success", true);
			ldb.set("reason", "保存数据成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}		

		return AJAX;
	}

	@Action(value="buildFormFields")
	public String buildFormFields() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		
		try{		
			if("u".equals(this.crud)){
				dynaBean = (HashMap<String, Object>)dynaBeanManager.getObject(tableName, this.item_guid);
			}else{
				dynaBean = new HashMap();
				int type = catalog.getType();
				String guid = new GUID().toString(32);
				if(type==2){
					dynaBean.put("reportinstance_guid", guid);
				}else{
					dynaBean.put("item_guid", guid);
					if(type==1){
						dynaBean.put("catalog_guid", node);
					}
				}
				if(this.item_parentguid!=null && this.item_parentguid.trim().length()>0){
					dynaBean.put("item_parentguid", this.item_parentguid);
				}				
			}
			
			this.json = catalogManager.buildFormFieldsConfig(tableName, dynaBean);
		}catch(Exception e){
			this.json = "";
		}
		
		return AJAX;
	}
	
	@Action(value="buildGridConfig")
	public String buildGridConfig() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, this.node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		
		StringBuilder gridConfig = new StringBuilder();		
		try{		
			gridConfig.append("{xtype: 'editorgrid', clicksToEdit: 1, id: 'gridId', border: true");
			gridConfig.append(",sm : sm");
			gridConfig.append(",viewConfig : {forceFit:false,autofill:true,emptyText:'没有数据!'}");
			gridConfig.append(",listeners : {'validateedit' : function(e){return false;}}");
			gridConfig.append(",loadMask : {msg:'正在获取数据，请稍等...'}");
			
			StringBuilder fieldsStore = new StringBuilder();
			StringBuilder fieldsCm = new StringBuilder();
			fieldsCm.append("sm,");
			
			List<DbColumn> lst = dbMetaDataManager.listAllColumns(tableName);
			for(DbColumn d : lst){
				String column_name = d.getColumn_name().trim().toLowerCase();
				String column_caption = d.getComment().trim().toLowerCase();
				boolean hidden = false;
				if(column_name.endsWith("guid")) hidden = true;
				
				switch(d.getData_type()){
				//整型
				case Types.TINYINT:
				case Types.SMALLINT:
				case Types.INTEGER:
				case Types.BIGINT:
					fieldsStore.append("{name: '" + column_name + "',type: 'int'},");
					fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "', editor: new Ext.form.NumberField({allowDecimals:false,decimalPrecision:4,allowNegative:false,allowBlank: true})},");
					break;
				//浮点型
				case Types.FLOAT:
				case Types.REAL:
				case Types.DOUBLE:
				case Types.NUMERIC:
				case Types.DECIMAL:
					fieldsStore.append("{name: '" + column_name + "',type: 'float'},");
					fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "', editor: new Ext.form.NumberField({allowDecimals:true,decimalPrecision:4,allowNegative:true,allowBlank: true})},");
					break;
				//字符串
				case Types.CHAR:
				case Types.VARCHAR:
//				case Types.NCHAR:
//				case Types.NVARCHAR:
					fieldsStore.append("{name: '" + column_name + "',type: 'string'},");
					fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', hidden : " + hidden + ", width: 100, sortable: true, dataIndex: '" + column_name + "', editor: new Ext.form.TextField({allowBlank: true})},");
					break;
				case Types.LONGVARCHAR:
//				case Types.LONGNVARCHAR:
					//fieldsStore.append("{name: '" + column_name + "',type: 'string'},");
					//fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "'},");
					break;
				//BOOLEAN
				case Types.BIT:
				case Types.BOOLEAN:
					fieldsStore.append("{name: '" + column_name + "',type: 'boolean'},");
					fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "', editor: new Ext.form.TextField({allowBlank: true})},");
					break;
				//日期型
				case Types.DATE:
					fieldsStore.append("{name: '" + column_name + "',type: 'date',dateFormat: 'Y-m-d H:i:s'},");
					fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "', renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s'), editor: new Ext.form.TextField({allowBlank: true})},");
					break;
				case Types.TIME:	
					fieldsStore.append("{name: '" + column_name + "',type: 'date',dateFormat: 'H:i:s'},");
					fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "', renderer: Ext.util.Format.dateRenderer('H:i:s'), editor: new Ext.form.TextField({allowBlank: true})},");
					break;
				case Types.TIMESTAMP:
					fieldsStore.append("{name: '" + column_name + "',type: 'date',dateFormat: 'Y-m-d H:i:s'},");
					fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "', renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s'), editor: new Ext.form.TextField({allowBlank: true})},");
					break;
				//blob
				case Types.BLOB:
					//fieldsStore.append("{name: '" + column_name + "',type: 'string'},");
					//fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "'},");
					break;
				//clob
				case Types.CLOB:
					//fieldsStore.append("{name: '" + column_name + "',type: 'string'},");
					//fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "'},");
					break;
				default:
					//fieldsStore.append("{name: '" + column_name + "',type: 'string'},");
					//fieldsCm.append("{id: '" + column_name + "', header: '" + column_caption + "', width: 100, sortable: true, dataIndex: '" + column_name + "'},");
				}
			}		
			String fieldsStore2 = fieldsStore.toString();
			String fieldsCm2 = fieldsCm.toString();
			if(fieldsStore2.endsWith(",")){
				fieldsStore2 = fieldsStore2.substring(0, fieldsStore2.length()-1);
			}
			if(fieldsCm2.endsWith(",")){
				fieldsCm2 = fieldsCm2.substring(0, fieldsCm2.length()-1);
			}
			gridConfig.append(",store : new Ext.data.Store({")
			.append("storeId : 'storeId'")
			.append(",url : '" + this.getContextPath() + "/admin/CatalogCrudAction/refreshJson.action?whichJson=getPagedCatalogItems'")
			.append(",autoLoad : {params: {start: 0,limit: 35} }")
			.append(",baseParams : {node: '" + this.node + "'}")
			.append(",reader: new Ext.data.JsonReader({")
			.append("  totalProperty : 'count'")
			.append("  ,root : 'list'")
			.append("  ,fields : [").append(fieldsStore2)
			.append("   ]")
			.append("  })")
			.append("})")
			.append(",columns : [").append(fieldsCm2).append("]")
			.append(",plugins: [new Ext.ux.netbox.core.FilterHeaderPlugin(filterModel)]")
			.append(",tbar: [{text: '自定义查询...', cls:'x-btn-text-icon',icon: '" + this.getContextPath() + "/images/system/fam/magnifier.png',iconAlign: 'top',handler: function(){win.show();} },{text: '确定', cls:'x-btn-text-icon',icon: '" + this.getContextPath() + "/images/system/fam/disk.png',iconAlign: 'top',handler: handlerButtonOk }]")
			.append(",bbar : new Ext.PagingToolbar({")
			.append("   store: Ext.StoreMgr.lookup('storeId')")
			.append("   ,id: 'pagingToolbarId'")
			.append("   ,pageSize: 35")
			.append("   ,displayInfo: true")
			.append("   ,plugins : new Ext.ux.Andrie.pPageSize()")
			.append("})")
			.append("}");
			
			this.json = gridConfig.toString(); 
		}catch(Exception e){
			this.json = "";
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="prepareSoItemAdd",
			results={@Result(name="success", location="/admin/catalog/soItemAdd.jsp")}
	)
	public String prepareSoItemAdd() throws Exception {
		try{
			catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return SUCCESS;
	}

	@Action(value="prepareSoItemEdit",
			results={@Result(name="success", location="/admin/catalog/soItemEdit.jsp")}
	)
	public String prepareSoItemEdit() throws Exception {
		try{
			catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
			String tableName = catalog.getTableName().trim().toLowerCase();
			
			dynaBean = (HashMap<String, Object>)dynaBeanManager.getObject(tableName, this.item_guid);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return SUCCESS;
	}

	public String prepareAdd() throws Exception {
		try{
			catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
			this.catalogCode = catalog.getCode();
			
			dynaBean = new HashMap<String,Object>();
			dynaBean.put("parentitem_guid", this.item_guid);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "prepareAdd";
	}
	
	@Action(value="prepareEdit",
			results={@Result(name="success", location="/admin/catalogcrud/crud/${catalogCode}-edit.jsp")}
	)
	public String prepareEdit() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		this.catalogCode = catalog.getCode();
		
		try{
			List<DbColumn> lst = dbMetaDataManager.listAllColumns(tableName);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy'_'MM'_'dd");
			
			dynaBean = (HashMap<String, Object>)dynaBeanManager.getObject(tableName, this.item_guid);
			Iterator it = dynaBean.keySet().iterator();
			while(it.hasNext()){
				String key = (String) it.next();
				Object o = dynaBean.get(key);
				if(o==null || o.toString().length()==0){
					for(DbColumn d : lst){
						if(d.getColumn_name().equalsIgnoreCase(key)){
							switch(d.getData_type()){
//						整型
							case Types.TINYINT:
							case Types.SMALLINT:
							case Types.INTEGER:
							case Types.BIGINT:
								dynaBean.put(key, Integer.valueOf(0));
								break;
//						浮点型
							case Types.FLOAT:
							case Types.REAL:
							case Types.DOUBLE:
							case Types.NUMERIC:
							case Types.DECIMAL:
								dynaBean.put(key, Integer.valueOf(0));
								break;
//						字符串
							case Types.CHAR:
							case Types.VARCHAR:
//							case Types.NCHAR:
//							case Types.NVARCHAR:
								dynaBean.put(key, String.valueOf(""));
								break;
							case Types.LONGVARCHAR:
//							case Types.LONGNVARCHAR:
								dynaBean.put(key, String.valueOf(""));
								break;
//						BOOLEAN
							case Types.BIT:
							case Types.BOOLEAN:
								dynaBean.put(key, Boolean.valueOf(false));
								break;
//						日期型
							case Types.DATE:
							case Types.TIME:								
								dynaBean.put(key, sdf.format(new Date()));
								break;
							case Types.TIMESTAMP:
								dynaBean.put(key, sdf.format(new Date()));
								break;
//						blob
							case Types.BLOB:
								//dynaBean.put(key, new Date());
								break;
//						clob
							case Types.CLOB:
								dynaBean.put(key, String.valueOf(""));
								break;
							default:
								dynaBean.put(key, String.valueOf(""));
							}
							break;
						}
					}
				}
			}	
			System.out.println(dynaBean.toString());
		}catch(Exception e){
			e.printStackTrace();
		}
		return SUCCESS;
	}

	@Action(value="add")
	public String add() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		LazyDynaBean ldb = new  LazyDynaBean();
		
		try{
			String guid = new GUID().toString();
			dynaBean.put("item_guid",guid);
			dynaBean.put("tabindex","2000");
			
			dynaBeanManager.saveObject(tableName, HibernateUtil.convertType(tableName, dynaBean,SystemConstants.REPORT_DYNAMODEL));		
			
			ldb.set("success", true);
			ldb.set("item_guid", guid);
			ldb.set("reason", "addCatalogItem success!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		return AJAX;
	}

	@Action(value="edit")
	public String edit() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		LazyDynaBean ldb = new  LazyDynaBean();
		
		try{
			dynaBeanManager.saveObject(tableName, HibernateUtil.convertType(tableName, dynaBean,SystemConstants.REPORT_DYNAMODEL));		
			
			ldb.set("success", true);
			ldb.set("reason", "editCatalogItem success!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		return AJAX;
	}

	@Action(value="validateFieldItem")
	public String validateFieldItem() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		LazyDynaBean ldb = new  LazyDynaBean();		
		try{
			if("dynaBean.item_code".equals(this.field)){
				List lst = dynaBeanManager.find("from " + tableName + " t where t.item_code = '" + this.value + "'");
				if("c".equals(this.crud)){
					if(lst.size()>0){
						ldb.set("success", true);
						ldb.set("valid", false);
						ldb.set("reason", "catalog的代码重复。");
						this.json = JSONObject.fromObject(ldb).toString();
						return "validateFieldItem";
					}
				}else{
					if(lst.size()>0){
						HashMap hm = (HashMap<String,Object>)lst.get(0);
						if(!((String)hm.get("item_guid")).equalsIgnoreCase(this.source)){
							ldb.set("success", true);
							ldb.set("valid", false);
							ldb.set("reason", "catalog的代码重复。");
							this.json = JSONObject.fromObject(ldb).toString();
							return "validateFieldItem";						
						}
					}
				}			
			}else if("dynaBean.item_name".equals(this.field)){
				List lst = dynaBeanManager.find("from " + tableName + " t where t.item_name = '" + this.value + "'");
				if("c".equals(this.crud)){
					if(lst.size()>0){
						ldb.set("success", true);
						ldb.set("valid", false);
						ldb.set("reason", "catalog的名称重复。");
						this.json = JSONObject.fromObject(ldb).toString();
						return "validateFieldItem";
					}
				}else{
					if(lst.size()>0){
						HashMap hm = (HashMap<String,Object>)lst.get(0);
						if(!((String)hm.get("item_guid")).equalsIgnoreCase(this.source)){
							ldb.set("success", true);
							ldb.set("valid", false);
							ldb.set("reason", "catalog的名称重复。");
							this.json = JSONObject.fromObject(ldb).toString();
							return "validateFieldItem";						
						}
					}
				}			
			}
			ldb.set("success", true);
			ldb.set("valid", true);
			ldb.set("reason", "validateFieldItem success");
			this.json = JSONObject.fromObject(ldb).toString();			
		}catch(Exception e){
			ldb.set("success", true);
			ldb.set("valid", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();			
		}
		return AJAX;
	}

	@Action(value="list",
			results={@Result(name="success", location="/admin/catalogcrud/crud/${catalogCode}-list.jsp")}
	)
	public String list() throws Exception {
		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		this.catalogCode = catalog.getCode();
		return SUCCESS;
	}

	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		long startTime = System.currentTimeMillis();

		catalog = (Catalog)catalogManager.getObject(Catalog.class, node);
		String tableName = catalog.getTableName().trim().toLowerCase();
		
		if(dbMetaDataManager.checkTableExist(tableName)){
			try{
				if("jsonFields".equalsIgnoreCase(this.whichJson)){
					List lst = dbMetaDataManager.listAllColumns(tableName);
					this.json = JSONUtil.getJsonString(null, null, lst);					
				}else if("jsonRelations".equalsIgnoreCase(this.whichJson)){
					List lst = dbMetaDataManager.listAllRelations(tableName);
					this.json = JSONUtil.getJsonString(null, null, lst);
				}else if("jsonIndexs".equalsIgnoreCase(this.whichJson)){
					List lst = dbMetaDataManager.listAllIndexs(tableName);
					this.json = JSONUtil.getJsonString(null, null, lst);
				}else if("jsonTypes".equalsIgnoreCase(this.whichJson)){
					List lst = dbMetaDataManager.listAllTypes();
					this.json = JSONUtil.getJsonString("include", "data_type,type_name", lst);
				}else if("getPagedCatalogItems".equalsIgnoreCase(this.whichJson)){
					Map map = null;
					if(filter==null || filter.trim().length()==0){						
						if(this.dynaBean==null){
							map = (Map)dynaBeanManager.getPagedCatalogItems(tableName, start, limit);
						}else{
							String where = "";
							List<DbColumn> listFields = dbMetaDataManager.listAllColumns(tableName);
							Set keys = this.dynaBean.keySet();
							for(Object key : keys){
								String fieldName = key.toString().trim().toLowerCase();
								Object fieldValue = this.dynaBean.get(key);
								Integer fieldType = null;
								for(DbColumn field : listFields){
									if(field.getColumn_name().equalsIgnoreCase(fieldName)){
										fieldType = field.getData_type();
										break;
									}
								}
								if(fieldType!=null && fieldValue!=null){
									switch(fieldType){
										case Types.TINYINT:
										case Types.SMALLINT:
										case Types.INTEGER:
										case Types.BIGINT:
										case Types.FLOAT:
										case Types.REAL:
										case Types.DOUBLE:
										case Types.NUMERIC:
										case Types.DECIMAL:											
											if(where.length()==0){
												where = fieldName + "=" + this.dynaBean.get(key).toString();
											}else{
												where += " AND " + fieldName + "=" + fieldValue.toString();
											}
											break;
										case Types.CHAR:
										case Types.VARCHAR:
										//case Types.NCHAR:
										//case Types.NVARCHAR:
											if(where.length()==0){
												where = fieldName + " like '%" + fieldValue.toString() + "%'";
											}else{
												where += " AND " + fieldName + " like '%" + fieldValue.toString() + "%'";
											}
											break;
										case Types.LONGVARCHAR:
										//case Types.LONGNVARCHAR:
											
											break;
										case Types.BIT:
										case Types.BOOLEAN:
											int bool = 0;
											if(fieldValue.toString().equalsIgnoreCase("yes")||fieldValue.toString().equalsIgnoreCase("true")||fieldValue.toString().equalsIgnoreCase("1")){
												bool = 1;
											}
											if(where.length()==0){
												where = fieldName + "=" + bool;
											}else{
												where += " AND " + fieldName + "=" + bool;
											}
											break;
										case Types.DATE:
											/*Calendar calendar = new GregorianCalendar();
											calendar.setTime(new Date());
											int year = calendar.get(Calendar.YEAR);
											int month = calendar.get(Calendar.MONTH) + 1;
											int day = calendar.get(Calendar.DAY_OF_MONTH);
											
											filter = "year(n.startTime)=" + year + " and month(n.startTime)=" + month + " and day(n.startTime)=" + day;*/
											break;
										case Types.TIME:								
											//dynaBean.put(key, sdf.format(new Date()));
											break;
										case Types.TIMESTAMP:
											//dynaBean.put(key, sdf.format(new Date()));
											break;
									}									
								}
							}
							map = (Map)dynaBeanManager.getPagedCatalogItems(tableName, where, start, limit);
						}
					}else{
						JsonFilterResolver filterResolver = new JsonFilterResolver();
						String where = filterResolver.getSql(JSONObject.fromObject(this.filter));
						map = (Map)dynaBeanManager.getPagedCatalogItems(tableName, where, start, limit);
					}
					this.json = JSONUtil.getJsonString(null,null,map);
				}else if("getPagedCatalogItemsByParentId".equalsIgnoreCase(this.whichJson)){
					Map map = dynaBeanManager.getPagedCatalogItemsByParentId(catalog, active_node_id, start, limit);
					this.json = JSONUtil.getJsonString("include", "count,list,item_guid,item_parentguid,item_code,item_name,_is_leaf,tabindex", map);
				}else if("jsonDictTypes".equalsIgnoreCase(this.whichJson)){
					List lst = dynaBeanManager.find("select distinct t.item_type from " + tableName + " t");
					ArrayList alist = new ArrayList();
					for(Object o : lst){
						Map map = new HashMap();
						map.put("guid", (String)o);
						map.put("item_type", (String)o);
						alist.add(map);
					}					
					this.json = JSONUtil.getJsonString(null, null, alist);
				}else if("jsonDictItems".equalsIgnoreCase(this.whichJson)){
					Map map = dynaBeanManager.getPagedDictItemsByType(tableName, source, start, limit);		
					this.json = JSONUtil.getJsonString(null, null, map);
				}else if("jsonSOinstances".equalsIgnoreCase(this.whichJson)){
					String filter = "";
					String condition = "t.item_guid not in (select m.so_instance_guid from SoCollectionMember m where m.so_guid='" + this.node + "' and m.soCollection.guid='" + this.source + "')";
					if(dynaBean!=null){
						Object item_name = dynaBean.get("item_name");
						Object item_code = dynaBean.get("item_code");
						if(item_name!=null && item_name.toString().trim().length()>0){
							filter = "t.item_name like '%" + item_name.toString().trim() + "%'";
						}
						if(item_code!=null && item_code.toString().trim().length()>0){							
							if(filter.length()==0){
								filter = "t.item_code like '%" + item_code.toString().trim() + "%'";
							}else{
								filter += " and t.item_code like '%" + item_code.toString().trim() + "%'";
							}
						}
					}
					if(filter.length()==0){
						filter = condition;
					}else{
						filter += " and " + condition;
					}

					//Map map = dynaBeanManager.getPagedSoInstances(tableName, "t", "new map(t.item_guid as item_guid,t.item_code as item_code,t.item_name as item_name,t.tabindex as tabindex)", filter, this.start, this.limit);
					Map map = dynaBeanManager.getPagedSoInstances(tableName, "t", "", filter, this.start, this.limit);
					this.json = JSONUtil.getJsonString(null, null, map);
				}else if("jsonSOinstances4User".equalsIgnoreCase(this.whichJson)){
					String filter = "";
					if(dynaBean!=null){
						Object item_name = dynaBean.get("item_name");
						Object item_code = dynaBean.get("item_code");
						if(item_name!=null && item_name.toString().trim().length()>0){
							filter = "t.item_name like '%" + item_name.toString().trim() + "%'";
						}
						if(item_code!=null && item_code.toString().trim().length()>0){							
							if(filter.length()==0){
								filter = "t.item_code like '%" + item_code.toString().trim() + "%'";
							}else{
								filter += " and t.item_code like '%" + item_code.toString().trim() + "%'";
							}
						}						
					}
					Map map = dynaBeanManager.getPagedSoItems(tableName, "t", filter, this.start, this.limit);
					this.json = JSONUtil.getJsonString(null, null, map);
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
		long endTime = System.currentTimeMillis();
		System.out.println("refreshJson Time Used："+(endTime-startTime));
		
		return AJAX;
	}
	
	
	public String getField() {
		return field;
	}
	public void setField(String field) {
		this.field = field;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public String getCrud() {
		return crud;
	}
	public void setCrud(String crud) {
		this.crud = crud;
	}
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}
	public Catalog getCatalog() {
		return catalog;
	}
	public void setCatalog(Catalog catalog) {
		this.catalog = catalog;
	}
	public CatalogManager getCatalogManager() {
		return catalogManager;
	}
	public void setCatalogManager(CatalogManager catalogManager) {
		this.catalogManager = catalogManager;
	}
	public HibernateLoader getHibernateLoader() {
		return hibernateLoader;
	}
	public void setHibernateLoader(HibernateLoader hibernateLoader) {
		this.hibernateLoader = hibernateLoader;
	}	
	public DbMetaDataManager getDbMetaDataManager() {
		return dbMetaDataManager;
	}
	public void setDbMetaDataManager(DbMetaDataManager dbMetaDataManager) {
		this.dbMetaDataManager = dbMetaDataManager;
	}		
	public DynaBeanManager getDynaBeanManager() {
		return dynaBeanManager;
	}
	public void setDynaBeanManager(DynaBeanManager dynaBeanManager) {
		this.dynaBeanManager = dynaBeanManager;
	}
	public HashMap<String,Object> getDynaBean() {
		return dynaBean;
	}
	public void setDynaBean(HashMap<String,Object> dynaBean) {
		this.dynaBean = dynaBean;
	}
	public String getItem_guid() {
		return item_guid;
	}
	public void setItem_guid(String item_guid) {
		this.item_guid = item_guid;
	}

	public String getCatalogCode() {
		return catalogCode;
	}

	public void setCatalogCode(String catalogCode) {
		this.catalogCode = catalogCode;
	}

	public String getItem_parentguid() {
		return item_parentguid;
	}

	public void setItem_parentguid(String item_parentguid) {
		this.item_parentguid = item_parentguid;
	}

	public String getFilter() {
		return filter;
	}

	public void setFilter(String filter) {
		this.filter = filter;
	}

	public ReportInstanceManager getReportInstanceManager() {
		return reportInstanceManager;
	}

	public void setReportInstanceManager(ReportInstanceManager reportInstanceManager) {
		this.reportInstanceManager = reportInstanceManager;
	}

}
